﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using T.FAS.Runtime.Base.Entity;
using T.FAS.Runtime.Metadata.Entity.DataModel;
using T.FAS.Runtime.StateMachine.SPI;

namespace T.FAS.Runtime.StateMachine.Engine
{
    class RequiredRuleProcess : IRuleProcess
    {
        public const string CSTKEY = "Required";

        public string Key => CSTKEY;

        public string Description => "必填";

        public List<ParamInfo> NeedParamInfo => null;

        public bool IsPreCheck => true;

        public bool Check(TRecord record, TState state, TRule rule, StateMachineMetadata metadata, StringBuilder failReason)
        {
            if (record == null || state == null || rule == null)
                return true;

            var targets = rule.RuleFields;
            bool result = true;
            if (targets != null && targets.Count > 0)
            {
                foreach (var targetObj in targets)
                {
                    if (targetObj == null) continue;
                    var target = targetObj.ColumnName;
                    var displayName = targetObj.DisplayName;
                    try
                    {
                        var valueNullErrorMsg = string.Format(CommonStringClass.RequiredRuleProcess_Check, displayName ?? target);
                        var data = record.GetValue(target);
                        if (data == null)
                        {
                            result = false;
                            failReason.AppendLine(valueNullErrorMsg);
                        }
                        else
                        {
                            if (data is JValue jVal)
                            {
                                data = jVal?.Value;
                            }
                            if (data is DBNull || string.IsNullOrEmpty(data?.ToString()))    //如果为字符串类型，进行空字符串判断
                            {
                                result = false;
                                failReason.AppendLine(valueNullErrorMsg);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        failReason.AppendLine(string.Format(CommonStringClass.RequiredRuleProcess_Check2, displayName ?? target));
                        return result;
                    }
                }
            }
            return result;
        }
    }
}
